<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
        fontSize: '14px',
        color: '#B2B2B2',
        lineHight: '20px',
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="billNo" required>
          <u--input v-model="model.billNo" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="proposer" required>
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.proposer"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.proposer"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="申请时间" required>
          <u--input v-model="model.createTime" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请部门" prop="proposerDeptId" required>
          <h-select-depart-input
            disabled
            v-model="model.proposerDeptId"
            :departName="model.proposerDeptText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.proposerDeptText"
          ></h-select-depart-input>
        </u-form-item>
        <u-form-item label="关联项目" prop="projectId" required>
          <h-select-project-input
            ref="projectSelect"
            v-model="model.projectId"
            style="width: 100%"
            placeholder="请选择项目名称"
            objectField="model.projectId"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            @input="queryBillByProject"
          ></h-select-project-input>
        </u-form-item>
        <u-form-item label="申请单位" prop="applicant" required>
          <h-select-company-input
            disabled
            style="width: 100%"
            v-model="model.applicant"
            border="surround"
            placeholder="请选择申请单位"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.applicant"
          ></h-select-company-input>
        </u-form-item>
        <u-form-item label="费用所属团队" prop="projectBusiTeamId">
          <h-select-team-input
            style="width: 100%"
            v-model="model.projectBusiTeamId"
            objectField="model.projectBusiTeamId"
            placeholder="请选择费用所属团队"
            border="surround"
            :tdlx="3"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-team-input>
        </u-form-item>
        <u-form-item label="业绩归属年度" prop="projectYear">
          <h-select-input-tag
            disabled
            class="w-100"
            v-model="model.projectYear"
            objectField="model.projectYear"
            placeholder="请选择业绩归属年度"
            border="surround"
            dictName="yjgsnd"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="本项目累计支付金额（元）" prop="projectPaidTotalAmount">
          <h-money-input disabled placeholder="请输入本项目累计支付金额" v-model="model.projectPaidTotalAmount"></h-money-input>
          <!-- <u--input
            type="number"
            disabled
            v-number-normal
            placeholder="请输入本项目累计支付金额"
            v-model="model.projectPaidTotalAmount"
          ></u--input> -->
        </u-form-item>
        <u-form-item label="本项目累计支付比例（%）" prop="projectPaidRate">
          <u--input
            type="number"
            disabled
            v-number-normal
            placeholder="请输入本项目累计支付比例"
            v-model="model.projectPaidRate"
          ></u--input>
        </u-form-item>
        <u-form-item label="是否垫付工程款" prop="isAdvance" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.isAdvance"
            objectField="model.isAdvance"
            placeholder="请选择是否垫付工程款"
            border="surround"
            dictName="YES_OR_NO"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="采购类别" prop="projectPurchaseCategories" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.projectPurchaseCategories"
            objectField="model.projectPurchaseCategories"
            placeholder="请选择采购类别"
            border="surround"
            dictName="purchase_categories"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="备注" prop="remark">
          <u--textarea v-model="model.remark" :confirm-type="null" maxlength="500" count placeholder="请输入备注"></u--textarea>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">建设方信息</view>
        <template v-if="model.ownerInfo.isRelConllectionContract == '1'">
          <u-form-item label="关联收款合同" prop="ownerInfo.conllectionContractId" required>
            <h-select-contract-manager-input-popup
              :disabled="!model.projectId"
              showName="1"
              htlx="1"
              :muitFlag="true"
              :projectId="model.projectId"
              v-model="model.ownerInfo.conllectionContractId"
              :placeholder="model.projectId ? '请选择关联收款合同' : '请先选择关联项目'"
              border="surround"
              style="width: 100%"
              suffixIcon="arrow-down-fill"
              :suffixIconStyle="{ color: '#B2B2B2' }"
              @change="getCollectContractInfo"
            ></h-select-contract-manager-input-popup>
          </u-form-item>
          <u-form-item label="建设单位合同金额（元）" prop="ownerInfo.ownerContractAmount">
            <h-money-input disabled placeholder="请输入建设单位合同金额" v-model="model.ownerInfo.ownerContractAmount"></h-money-input>
            <!-- <u--input
              disabled
              type="number"
              v-number-normal
              placeholder="请输入建设单位合同金额"
              v-model="model.ownerInfo.ownerContractAmount"
            ></u--input> -->
          </u-form-item>
        </template>
        <u-form-item label="建设单位调整后合同金额（元）" prop="ownerInfo.ownerAdjustedContractAmount" required>
          <h-money-input
            placeholder="请输入建设单位调整后合同金额"
            v-model="model.ownerInfo.ownerAdjustedContractAmount"
            @input="inputReturnedAmount"
          ></h-money-input>
          <!-- <u--input
            type="number"
            v-number-normal
            placeholder="请输入建设单位调整后合同金额"
            v-model="model.ownerInfo.ownerAdjustedContractAmount"
            @change="inputReturnedAmount"
          ></u--input> -->
        </u-form-item>
        <u-form-item label="建设单位已回款金额（元）" prop="ownerInfo.ownerReturnedAmount" required>
          <h-money-input
            placeholder="请输入建设单位已回款金额"
            :max="model.ownerInfo.ownerAdjustedContractAmount"
            v-model="model.ownerInfo.ownerReturnedAmount"
            @input="inputReturnedAmount"
          ></h-money-input>
          <!-- <u--input
            type="number"
            v-number-normal
            placeholder="请输入建设单位已回款金额"
            v-model="model.ownerInfo.ownerReturnedAmount"
            @change="inputReturnedAmount"
          ></u--input> -->
        </u-form-item>
        <u-form-item label="建设单位已回款比例%" prop="ownerInfo.ownerReturnedRate">
          <u--input
            disabled
            type="number"
            v-number-normal
            placeholder="请输入建设单位已回款比例%"
            v-model="model.ownerInfo.ownerReturnedRate"
          ></u--input>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">施工方信息</view>
        <u-form-item label="关联付款合同" prop="constructInfo.paymentContractId" required>
          <h-select-contract-manager-input-popup
            :disabled="!model.projectId"
            htlx="2"
            :projectId="model.projectId"
            v-model="model.constructInfo.paymentContractId"
            :placeholder="model.projectId ? '请选择关联付款合同' : '请先选择关联项目'"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            @change="getContractInfo"
          ></h-select-contract-manager-input-popup>
        </u-form-item>
        <u-form-item label="施工方合同金额（元）" prop="constructInfo.constructionContractAmount">
          <h-money-input
            disabled
            placeholder="请输入施工方合同金额"
            v-model="model.constructInfo.constructionContractAmount"
          ></h-money-input>
          <!-- <u--input
            disabled
            type="number"
            v-number-normal
            placeholder="请输入施工方合同金额"
            v-model="model.constructInfo.constructionContractAmount"
          ></u--input> -->
        </u-form-item>
        <u-form-item label="施工方调整后合同金额（元）" prop="constructInfo.constructionAdjustedContractAmount" required>
          <h-money-input
            placeholder="请输入施工方调整后合同金额"
            @input="inputAmount"
            v-model="model.constructInfo.constructionAdjustedContractAmount"
          ></h-money-input>
          <!-- <u--input
            type="number"
            v-number-normal
            placeholder="请输入施工方调整后合同金额"
            v-model="model.constructInfo.constructionAdjustedContractAmount"
            @change="inputAmount"
          ></u--input> -->
        </u-form-item>
        <u-form-item label="已开票累计金额（元）" prop="constructInfo.invoicedTotalAmount">
          <h-money-input placeholder="请输入已开票累计金额" v-model="model.constructInfo.invoicedTotalAmount"></h-money-input>
          <!-- <u--input
            type="number"
            v-number-normal
            placeholder="请输入已开票累计金额"
            v-model="model.constructInfo.invoicedTotalAmount"
          ></u--input> -->
        </u-form-item>
        <u-form-item label="已支付金额（元）" prop="constructInfo.paidAmount">
          <h-money-input disabled placeholder="请输入已支付金额" v-model="model.constructInfo.paidAmount"></h-money-input>
          <!-- <u--input
            type="number"
            disabled
            v-number-normal
            placeholder="请输入已支付金额"
            v-model="model.constructInfo.paidAmount"
          ></u--input> -->
        </u-form-item>
        <u-form-item label="发票类型" prop="constructInfo.isSpecialInvoice" required>
          <h-select-input-tag
            class="w-100"
            @change="isSpecial"
            v-model="model.constructInfo.isSpecialInvoice"
            objectField="model.constructInfo.isSpecialInvoice"
            placeholder="请选择类型"
            border="surround"
            dictName="invoice_type"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="报销金额（元）" prop="constructInfo.reimbursementAmount" required>
          <h-money-input
            placeholder="请输入报销金额"
            @input="inputTaxAmount"
            :max="model.constructInfo.constructionAdjustedContractAmount"
            v-model="model.constructInfo.reimbursementAmount"
          ></h-money-input>
          <!-- <u--input
            type="number"
            v-number-normal
            placeholder="请输入报销金额"
            @change="inputTaxAmount"
            v-model="model.constructInfo.reimbursementAmount"
          ></u--input> -->
        </u-form-item>
        <u-form-item label="税费金额（元）" prop="constructInfo.taxAmount" :required="isSpecialRequired">
          <h-money-input
            :disabled="isSpecialDisabled || !isSpecialRequired"
            :max="model.constructInfo.reimbursementAmount"
            placeholder="请输入税费金额"
            v-model="model.constructInfo.taxAmount"
            @input="inputTaxAmount"
          ></h-money-input>
          <!-- <u--input
            type="number"
            v-number-normal
            placeholder="请输入税费金额"
            @change="inputTaxAmount"
            v-model="model.constructInfo.taxAmount"
          ></u--input> -->
        </u-form-item>
        <u-form-item label="未税金额（元）" prop="constructInfo.untaxedAmount">
          <h-money-input
            disabled
            placeholder="请输入未税金额"
            v-model="model.constructInfo.untaxedAmount"
            @input="inputTaxAmount"
          ></h-money-input>
          <!-- <u--input
            disabled
            type="number"
            v-number-normal
            placeholder="请输入未税金额"
            @change="inputTaxAmount"
            v-model="model.constructInfo.untaxedAmount"
          ></u--input> -->
        </u-form-item>
        <u-form-item label="本次支付金额（元）" prop="constructInfo.currentPaymentAmount" required>
          <h-money-input
            :max="model.constructInfo.constructionAdjustedContractAmount"
            placeholder="请输入本次支付金额"
            v-model="model.constructInfo.currentPaymentAmount"
            @input="inputAmount"
          ></h-money-input>
          <!-- <u--input
            type="number"
            v-number-normal
            placeholder="请输入本次支付金额"
            v-model="model.constructInfo.currentPaymentAmount"
          ></u--input> -->
        </u-form-item>
        <u-form-item label="本次支付比例（%）" prop="constructInfo.currentPaymentRate">
          <u--input
            disabled
            type="number"
            v-number-normal
            placeholder="请输入本次支付比例"
            v-model="model.constructInfo.currentPaymentRate"
          ></u--input>
        </u-form-item>
        <u-form-item label="累计支付金额（元）" prop="constructInfo.paidTotalAmount">
          <h-money-input disabled placeholder="请输入累计支付金额" v-model="model.constructInfo.paidTotalAmount"></h-money-input>
          <!-- <u--input
            type="number"
            disabled
            v-number-normal
            placeholder="请输入累计支付金额"
            v-model="model.constructInfo.paidTotalAmount"
          ></u--input> -->
        </u-form-item>
        <u-form-item label="累计支付比例（%）" prop="constructInfo.paidTotalRate">
          <u--input
            type="number"
            disabled
            v-number-normal
            placeholder="请输入累计支付比例"
            v-model="model.constructInfo.paidTotalRate"
          ></u--input>
        </u-form-item>
        <u-form-item label="付款方式" prop="constructInfo.payMode" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.constructInfo.payMode"
            objectField="model.constructInfo.payMode"
            placeholder="请选择付款方式"
            border="surround"
            dictName="pay_mode"
            @change="radioModeChange"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="收款单位" prop="constructInfo.payeeName" required>
					<h-select-customer-input-popup
						style="width: 100%"
						v-model="model.constructInfo.payeeName"
						commercialType="2"
						placeholder="请选择收款单位"
						:isJudge='true'
						@onJudge='onJudge'
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
					/>
        </u-form-item>
        <template v-if="model.constructInfo.payMode == '1'">
          <u-form-item label="开户行" prop="constructInfo.bankName">
            <u--input disabled placeholder="请输入开户行" v-model="model.constructInfo.bankName"></u--input>
          </u-form-item>
          <u-form-item label="账户" prop="constructInfo.accountNo">
            <u--input disabled placeholder="请输入账户" v-model="model.constructInfo.accountNo"></u--input>
          </u-form-item>
        </template>
        <u-form-item label="备注" prop="remark">
          <u--textarea
            v-model="model.constructInfo.remark"
            :confirm-type="null"
            maxlength="500"
            count
            placeholder="请输入备注"
          ></u--textarea>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">附件信息</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.attachments" :isIcon="false"></h-upload-file>
          <file-list v-if="model.attachments" v-model="model.attachments" :isDelete="true"></file-list>
        </view>
      </view>

      <view class="space-x-1 px-1 btn_position">
        <u-button :disabled="isSubmit" type="primary" :plain="true" text="保存" @click="onDraft"></u-button>
        <u-button :disabled="isSubmit" type="primary" text="保存并提交" @click="onSubmit"></u-button>
      </view>
      <view style="height: 100rpx"></view>
    </u-form>

    <u-toast ref="uToast"></u-toast>
    <ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
    <!-- <u-modal
      :show="confirmModal"
      title="是否确认"
      :closeOnClickOverlay="true"
      :asyncClose="true"
      @cancel="handleConfirmModalCancel"
      @confirm="handleConfirmModalConfirm"
      showCancelButton
    >
      <view class="slot-content">
        <view>是否确认切换所属团队，此操作将会清空还款明细中已填写的所有信息？</view>
      </view>
    </u-modal> -->
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import {
  gainBillNo,
  add,
  edit,
  info,
  queryBillByProject,
  queryLastApplyByContractId,
  queryBillByContract,
  findInvoiceAmountCount,
} from '@/api/finance/ErpFinanceProjectProgressPaymentApplicationBillForm'
import { filterMultiDictText, initDictOptions } from '@/utils/JDictSelectUtil.js'
import fileList from '@/pages/synergy/components/fileList.vue'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗

export default {
  name: 'ErpFinanceProjectProgressPaymentApplicationBillForm',
  components: { fileList, ProcessNodeConfiguration },
  data() {
    return {
      payeeUnitBackUp: null,
      projectPaidTotalAmount: 0, // 项目累计金额
      paidTotalAmount: 0, // 施工方累计金额
      constructTotalAmount: 0, // 所有施工方调整后合同金额累计
      isSpecialDisabled: false,
      isSpecialRequired: false,
      isSubmit: false,
      backUpApplicant: '',
      backUpTeamId: '',
      // isReset: false,
      // resetKey: '',
      index: null,
      // showFormModal: false,
      // confirmModal: false,
      loading: false,
      id: '',
      model: {
        // 基本信息 - 公用
        bpmBizTitle: '',
        billNo: '',
        proposer: '',
        proposerDeptId: '',
        createTime: '',
        applicant: '',
        projectId: '',
        projectBusiTeamId: '',
        projectYear: '',
        projectPaidTotalAmount: '',
        projectPaidRate: '',
        isAdvance: '',
        projectPurchaseCategories: '',
        remark: '',
        // 基本信息 - 非公用
        ownerInfo: {
          isRelConllectionContract: '1',
          conllectionContractId: '',
          ownerContractAmount: '',
          ownerAdjustedContractAmount: '',
          ownerReturnedAmount: '',
          ownerReturnedRate: '',
        },
        constructInfo: {
          isRelPaymentContract: '1',
          paymentContractId: '',
          constructionContractAmount: '',
          constructionAdjustedContractAmount: '',
          invoicedTotalAmount: '',
          paidAmount: '',
          isSpecialInvoice: '',
          reimbursementAmount: '',
          taxAmount: '',
          untaxedAmount: '',
          currentPaymentAmount: '',
          currentPaymentRate: '',
          paidTotalAmount: '',
          paidTotalRate: '',
          payMode: '',
          payeeName: '',
          bankName: '',
          accountNo: '',
          remark: '',
        },
        // 附件
        attachments: null,
      },
      formData: [],
      rules: {
        bpmBizTitle: [{ required: true, message: '请输入流程标题!', trigger: ['blur', 'change'] }],
        billNo: [
          {
            required: true,
            message: '请输入单据编号!',
            trigger: ['blur', 'change'],
          },
        ],
        proposerDeptId: [
          {
            required: true,
            message: '请选择申请部门!',
            trigger: ['blur', 'change'],
          },
        ],
        proposer: [
          {
            required: true,
            message: '请选择申请人!',
            trigger: ['blur', 'change'],
          },
        ],
        createTime: [
          {
            required: true,
            message: '请选择申请时间!',
            trigger: ['blur', 'change'],
          },
        ],
        applicant: [{ required: true, message: '请选择申请单位!', trigger: ['blur', 'change'] }],
        projectId: [{ required: true, message: '请选择关联项目!', trigger: ['blur', 'change'] }],
        isAdvance: [{ required: true, message: '请选择是否垫付工程款!', trigger: ['blur', 'change'] }],
        projectPurchaseCategories: [{ required: true, message: '请选择采购类别!', trigger: ['blur', 'change'] }],
        'ownerInfo.isRelConllectionContract': [{ required: true, message: '请选择是否关联收款合同!', trigger: ['blur', 'change'] }],
        'ownerInfo.conllectionContractId': [{ required: true, message: '请选择收款合同!', trigger: ['blur', 'change'] }],
        'ownerInfo.ownerAdjustedContractAmount': [
          {
            required: true,
            pattern: /^(?!0\.00)(?!0$)([1-9]\d*|0)(\.\d{2})?$/,
            message: '请输入建设单位调整后合同金额!',
            trigger: ['blur', 'change'],
          },
        ],
        'ownerInfo.ownerReturnedAmount': [
          {
            required: true,
            pattern: /^(?!0\.00)(?!0$)([1-9]\d*|0)(\.\d{2})?$/,
            message: '请输入建设单位已回款金额!',
            trigger: ['blur', 'change'],
          },
        ],
        'constructInfo.isRelPaymentContract': [{ required: true, message: '请选择是否关联付款合同!', trigger: ['blur', 'change'] }],
        'constructInfo.paymentContractId': [{ required: true, message: '请选择付款合同!', trigger: ['blur', 'change'] }],
        'constructInfo.constructionAdjustedContractAmount': [
          {
            required: true,
            pattern: /^(?!0\.00)(?!0$)([1-9]\d*|0)(\.\d{2})?$/,
            message: '请输入施工方调整后合同金额!',
            trigger: ['blur', 'change'],
          },
        ],
        'constructInfo.isSpecialInvoice': [{ required: true, message: '请选择发票类型!', trigger: ['blur', 'change'] }],
        'constructInfo.reimbursementAmount': [
          {
            required: true,
            pattern: /^(?!0\.00)(?!0$)([1-9]\d*|0)(\.\d{2})?$/,
            message: '请输入报销金额!',
            trigger: ['blur', 'change'],
          },
        ],
        'constructInfo.payMode': [{ required: true, message: '请选择付款方式!', trigger: ['blur', 'change'] }],
        'constructInfo.payeeName': [{ required: true, message: '请选择收款单位!', trigger: ['blur', 'change'] }],
        'constructInfo.purchaseCategories': [{ required: true, message: '请选择采购类别!', trigger: ['blur', 'change'] }],
        'constructInfo.currentPaymentAmount': [
          {
            required: true,
            pattern: /^(?!0\.00)(?!0$)([1-9]\d*|0)(\.\d{2})?$/,
            message: '请输入本次支付金额!',
            trigger: ['blur', 'change'],
          },
        ],
        'constructInfo.invoicedTotalAmount': [
          {
            required: false,
            pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/,
            message: '请输入正确的金额!',
            trigger: ['blur', 'change'],
          },
        ],
        // 'constructInfo.taxAmount': [
        //   {
        //     required: true,
        //     pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/,
        //     message: '请输入正确的金额!',
        //     trigger: ['blur', 'change'],
        //   },
        // ],
      },
      dictOptions: {},
      flowCode: 'onl_erp_finance_project_progress_payment_application_bill',
      formUrl: '/erp/finance/projectProgress/modules/ErpFinanceProjectProgressPaymentApplicationBillForm',
      formUrlMobile: '/pages/synergy/erpProjectProgressPaymentApplicationBillList',
      processId: '1522138061967843329',
      beanName: 'erpFinanceProjectProgressPaymentApplicationBillServiceImpl',
    }
  },
  onLoad({ id }) {
    this.id = id || ''
  },
  created() {
    if (this.id) {
      this.initInfo()
    } else {
      this.initForm()
      this.initBillNo()
      this.isSpecial()
    }
    this.initDicts()
  },
  computed: {
    ...mapState(['userInfo']),
    formTotal() {
      return this.formData.reduce((total, item) => total + Number(item.amount), 0).toFixed(2)
    },
  },
  methods: {
    initDicts() {
      initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
        if (res.success) {
          this.$set(this.dictOptions, 'teamManager', res.result)
        }
      })
    },
    // 获取同等合同下的单据信息
    getContractInfo(item) {
      if (item) {
        this.$set(this.model.constructInfo, 'constructionAdjustedContractAmount', item.bchte)
				let that = this
				// 获取本合同的累计金额
				queryBillByContract({ contractId: this.model.constructInfo.paymentContractId }).then((res) => {
				  if (res.success) {
				    let data = res.result
				    this.$set(this.model.constructInfo, 'paidAmount', data)
				    if (this.model.constructInfo.currentPaymentAmount) {
				      this.$set(this.model.constructInfo, 'paidTotalAmount', (data + Number(this.model.constructInfo.currentPaymentAmount)).toFixed(2))
				    } else {
				      this.$set(this.model.constructInfo, 'paidTotalAmount', data)
				    }
				    this.paidTotalAmount = data
				  }
				})
				// 获取累计开票金额
				findInvoiceAmountCount({ projectContract: this.model.constructInfo.paymentContractId }).then((res) => {
				  if (res.success) {
				    let data = res.result
				    if (data) {
				      this.$set(this.model.constructInfo, 'invoicedTotalAmount', data)
				    } else {
				      this.$set(this.model.constructInfo, 'invoicedTotalAmount', 0)
				    }
				  }
				  // 获取付款后金额
				  queryLastApplyByContractId({ contractNo: item.htbh }).then((res) => {
				    if (res.success) {
				      let resdata = res.result
				      if (resdata) {
				        this.$set(this.model.constructInfo, 'constructionContractAmount', resdata.bchte)
				      } else {
				        this.$set(this.model.constructInfo, 'constructionContractAmount', item.bchte)
				      }
				    } else {
				      this.$set(this.model.constructInfo, 'constructionContractAmount', item.bchte)
				    }
				  })
				})
      } else {
				this.$set(this.model.constructInfo, 'constructionAdjustedContractAmount', '')
				this.$set(this.model.constructInfo, 'paidAmount', '')
				this.$set(this.model.constructInfo, 'paidTotalAmount', '')
				this.paidTotalAmount = 0
				this.$set(this.model.constructInfo, 'invoicedTotalAmount', '')
				this.$set(this.model.constructInfo, 'constructionContractAmount', '')
			}
      this.inputAmount()
    },
    //获取收款合同信息
    getCollectContractInfo([data]) {
      if (data) {
        this.$set(this.model.ownerInfo, 'ownerAdjustedContractAmount', data.bchte)
        this.$set(this.model.ownerInfo, 'ownerReturnedAmount', data.realCollectionPaymentMoney)
        //获取之前审核的金额
        queryLastApplyByContractId({ contractNo: data.htbh })
          .then((res) => {
            if (res.success) {
              let resdata = res.result
              if (resdata) {
                this.$set(this.model.ownerInfo, 'ownerContractAmount', resdata.bchte)
              } else {
                this.$set(this.model.ownerInfo, 'ownerContractAmount', data.bchte)
              }
            } else {
              this.$set(this.model.ownerInfo, 'ownerContractAmount', data.bchte)
            }
          })
          .catch((error) => {
            this.$set(this.model.ownerInfo, 'ownerContractAmount', data.bchte)
          })
        this.inputReturnedAmount()
      } else {
				this.$set(this.model.ownerInfo, 'ownerAdjustedContractAmount', '')
				this.$set(this.model.ownerInfo, 'ownerReturnedAmount', '')
				this.$set(this.model.ownerInfo, 'ownerContractAmount', '')
				this.$set(this.model.ownerInfo, 'ownerReturnedRate', '')
			}
    },
		onJudge(){
			// 保存返回的监听，事先处理好
			uni.$on("supplierBack", res => {
				this.model.constructInfo.payeeName = res.id
				this.selectCustomer(res)
				
				// 清除监听
				uni.$off('supplierBack');
			})
			uni.navigateTo({
				url:'/pages/common/selectSupplier/selectSupplierInput'+'?isProPayContract=1&isNoJudge=1'
			})
		},
		//选择单位
		selectCustomer(data) {
		  if (data) {
		    this.$set(this.model.constructInfo, 'bankName', data.bankName)
		    this.$set(this.model.constructInfo, 'accountNo', data.bankAccountNo)
		  }
		},
    //切换方式
    radioModeChange(data) {
      if (data == '2') {
        this.$set(this.model.constructInfo, 'accountNo', null)
        this.$set(this.model.constructInfo, 'bankName', null)
      } else {
        const item = this.payeeUnitBackUp
        if (item && item.id && item.id === this.model.constructInfo.payeeName) {
          // 回显
          item && item.bankAccountNo && this.$set(this.model.constructInfo, 'accountNo', item.bankAccountNo)
          item && item.bankName && this.$set(this.model.constructInfo, 'bankName', item.bankName)
        }
      }
    },
    //获取收款单位信息
    getCustomerInfo(data) {
      if (data) {
        this.payeeUnitBackUp = data
        this.$set(this.model.constructInfo, 'accountNo', data.bankAccountNo)
        this.$set(this.model.constructInfo, 'bankName', data.bankName)
      }
    },
    //修改本次支付金额
    inputAmount() {
      let currentPaymentAmount = Number(this.model.constructInfo.currentPaymentAmount) //本次支付金额
      let constructionAdjustedContractAmount = Number(this.model.constructInfo.constructionAdjustedContractAmount) //合同调整金额
      let paidTotalAmount = Number(this.paidTotalAmount) //累计支付金额
      let currentPaymentRate = ((currentPaymentAmount / constructionAdjustedContractAmount).toFixed(4) * 100).toFixed(2) //本次支付比例
      let constructTotalAmount = Number(this.constructTotalAmount != 0 ? this.constructTotalAmount : constructionAdjustedContractAmount) //所有施工方金额
      let projectPaidTotalAmount = Number(this.projectPaidTotalAmount) //项目总支付金额
      if (
        (!!projectPaidTotalAmount || projectPaidTotalAmount == 0) &&
        (currentPaymentAmount !== null || currentPaymentAmount !== '' || currentPaymentAmount !== undefined)
      ) {
        this.$set(this.model, 'projectPaidTotalAmount', (projectPaidTotalAmount + currentPaymentAmount).toFixed(2))
        if (constructTotalAmount) {
          this.$set(
            this.model,
            'projectPaidRate',
            (((projectPaidTotalAmount + currentPaymentAmount) / constructTotalAmount).toFixed(4) * 100).toFixed(2),
          )
        }
      }
      if (
        (!!paidTotalAmount || paidTotalAmount == 0) &&
        (currentPaymentAmount !== null || currentPaymentAmount !== '' || currentPaymentAmount !== undefined)
      ) {
        this.$set(this.model.constructInfo, 'paidTotalAmount', (paidTotalAmount + currentPaymentAmount).toFixed(2))
        if (constructionAdjustedContractAmount) {
          this.$set(
            this.model.constructInfo,
            'paidTotalRate',
            (((paidTotalAmount + currentPaymentAmount) / constructionAdjustedContractAmount).toFixed(4) * 100).toFixed(2),
          )
        }
      }
      if (
        !!constructionAdjustedContractAmount &&
        (currentPaymentAmount !== null || currentPaymentAmount !== '' || currentPaymentAmount !== undefined)
      ) {
        this.$set(this.model.constructInfo, 'currentPaymentRate', currentPaymentRate)
      }
    },
    //税
    inputTaxAmount() {
      let constructInfo = this.model.constructInfo
      if (constructInfo.reimbursementAmount || constructInfo.reimbursementAmount == 0) {
        if (constructInfo.taxAmount || constructInfo.taxAmount == 0) {
          constructInfo.untaxedAmount = (constructInfo.reimbursementAmount - constructInfo.taxAmount).toFixed(2)
        }
      }
    },
    //发票类型
    isSpecial() {
      if (this.model.constructInfo.isSpecialInvoice == 0 && this.model.constructInfo.isSpecialInvoice != '') {
        //不是专票
        this.$set(this.model.constructInfo, 'taxAmount', 0)
        this.isSpecialRequired = false
        this.isSpecialDisabled = true
        this.inputTaxAmount()
        if(this.rules['constructInfo.taxAmount']) {
          this.$refs.form.clearValidate('constructInfo.taxAmount')
        }
        this.$set(this.rules, 'constructInfo.taxAmount', [
          {
            required: false,
            pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/,
            message: '请输入正确的金额!',
            trigger: ['blur', 'change'],
          },
        ])
      } else {
        this.isSpecialRequired = true
        this.isSpecialDisabled = false
        if(this.rules['constructInfo.taxAmount']) {
          this.$refs.form.clearValidate('constructInfo.taxAmount')
        }
        this.$set(this.rules, 'constructInfo.taxAmount', [
          {
            required: true,
            pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/,
            message: '请输入正确的金额!',
            trigger: ['blur', 'change'],
          },
        ])
      }
    },
    //汇款金额判断
    inputReturnedAmount() {
      let ownerAdjustedContractAmount = this.model.ownerInfo.ownerAdjustedContractAmount //调整金额
      let ownerReturnedAmount = this.model.ownerInfo.ownerReturnedAmount //回款金额
      if (!!ownerAdjustedContractAmount && !!ownerReturnedAmount) {
        this.$set(
          this.model.ownerInfo,
          'ownerReturnedRate',
          ((ownerReturnedAmount / ownerAdjustedContractAmount).toFixed(4) * 100).toFixed(2),
        )
      }
    },
    queryBillByProject(item) {
      this.$set(this.model, 'applicant', item.signUnit)
      this.$set(this.model, 'projectYear', item.year)
      this.$set(this.model, 'projectBusiTeamId', item.teamName)

      // 判断是否关联收款合同
      if (this.model.ownerInfo.isRelConllectionContract == '0') {
        this.$set(this.model.ownerInfo, 'ownerAdjustedContractAmount', null)
        this.$set(this.model.ownerInfo, 'ownerReturnedAmount', null)
        this.$set(this.model.ownerInfo, 'ownerReturnedRate', '')
      } else {
        if (this.model.ownerInfo.conllectionContractId) {
          this.$set(this.model.ownerInfo, 'conllectionContractId', null)
          this.$set(this.model.ownerInfo, 'ownerContractAmount', null)
        }
        this.$set(this.model.ownerInfo, 'ownerAdjustedContractAmount', null)
        this.$set(this.model.ownerInfo, 'ownerReturnedAmount', null)
        this.$set(this.model.ownerInfo, 'ownerReturnedRate', '')
      }
      // 判断是否关联付款合同
      if (this.model.constructInfo.isRelPaymentContract == '0') {
        this.$set(this.model.constructInfo, 'constructionAdjustedContractAmount', null)
        this.$set(this.model.constructInfo, 'invoicedTotalAmount', null)
        this.$set(this.model.constructInfo, 'paidAmount', null)
        this.$set(this.model.constructInfo, 'isSpecialInvoice', null)
        this.$set(this.model.constructInfo, 'reimbursementAmount', null)
        this.$set(this.model.constructInfo, 'taxAmount', null)
        this.$set(this.model.constructInfo, 'untaxedAmount', null)
        this.$set(this.model.constructInfo, 'currentPaymentAmount', null)
        this.$set(this.model.constructInfo, 'currentPaymentRate', '')
        this.$set(this.model.constructInfo, 'paidTotalAmount', null)
        this.$set(this.model.constructInfo, 'paidTotalRate', '')
        this.$set(this.model.constructInfo, 'payMode', null)
        this.$set(this.model.constructInfo, 'payeeName', null)
        this.$set(this.model.constructInfo, 'bankName', '')
        this.$set(this.model.constructInfo, 'accountNo', '')
      } else {
        if (this.model.constructInfo.paymentContractId) {
          this.$set(this.model.constructInfo, 'paymentContractId', null)
          this.$set(this.model.constructInfo, 'constructionContractAmount', null)
        }
        this.$set(this.model.constructInfo, 'constructionAdjustedContractAmount', null)
        this.$set(this.model.constructInfo, 'invoicedTotalAmount', null)
        this.$set(this.model.constructInfo, 'paidAmount', null)
        this.$set(this.model.constructInfo, 'isSpecialInvoice', null)
        this.$set(this.model.constructInfo, 'reimbursementAmount', null)
        this.$set(this.model.constructInfo, 'taxAmount', null)
        this.$set(this.model.constructInfo, 'untaxedAmount', null)
        this.$set(this.model.constructInfo, 'currentPaymentAmount', null)
        this.$set(this.model.constructInfo, 'currentPaymentRate', '')
        this.$set(this.model.constructInfo, 'paidTotalAmount', null)
        this.$set(this.model.constructInfo, 'paidTotalRate', '')
        this.$set(this.model.constructInfo, 'payMode', null)
        this.$set(this.model.constructInfo, 'payeeName', null)
        this.$set(this.model.constructInfo, 'bankName', '')
        this.$set(this.model.constructInfo, 'accountNo', '')
      }

      queryBillByProject({ projectId: this.model.projectId }).then((res) => {
        if (res.success) {
          let data = res.result
          if (data) {
            this.$set(this.model, 'projectPaidTotalAmount', data.projectTotalAmount)
            this.projectPaidTotalAmount = data.projectTotalAmount
            this.constructTotalAmount = data.constructAmount
          }
        }
      })
    },
    // 获取单据编号
    async initBillNo() {
      const res = await gainBillNo({ proposer: this.userInfo.empId })
      this.model.billNo = res.result
      this.model.bpmBizTitle = this.userInfo?.employee?.name + '-' + this.model.billNo //标题
    },
    // 初始化新增需要的数据
    initForm() {
      this.model.proposer = this.userInfo.empId //当前登录人
      this.model.proposerDeptId = this.userInfo.deptId //当前登录人部门
      this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
      this.model.payee = this.userInfo.empId //领款人
    },
    async initInfo() {
      const response = await info({ id: this.id })
      const data = response?.result || {}
      this.model = Object.assign({}, data)
      this.initData()
    },
    initData() {
      // 编辑时重新获取支付累计金额
      if (this.model.constructInfo.paymentContractId) {
        // 获取本合同的累计金额
        queryBillByContract({ contractId: this.model.constructInfo.paymentContractId }).then((res) => {
          if (res.success) {
            let data = res.result
            this.paidTotalAmount = data
          }
        })
      }
      // 编辑时重新获取项目累计支付金额
      if (this.model.projectId) {
        queryBillByProject({ projectId: this.model.projectId }).then((res) => {
          if (res.success) {
            let data = res.result
            if (data) {
              this.projectPaidTotalAmount = data.projectTotalAmount
              this.constructTotalAmount = data.constructAmount
            }
          }
        })
      }
      this.isSpecial()
    },
    validateForm() {
      return this.$refs.form.validate()
    },
    getCreateTime() {
      let createTime = this.model.createTime
      let date = createTime.substring(0, 10)
      return date.substring(0, 4) + '年' + date.substring(5, 7) + '月' + date.substring(8, 10) + '日'
    },
    setBpmBizTitle() {
      let teamName = filterMultiDictText(this.dictOptions['teamManager'], this.model.projectBusiTeamId + '')
      let createTime = this.getCreateTime()
      //迭代16.7 取费用所属团队-申请人-申请日期（年月日）-金额（取报销金额）
      this.model.bpmBizTitle =
        (teamName? teamName+ ' - ':'') + this.userInfo?.employee?.name + ' - ' + createTime + (this.model.constructInfo.reimbursementAmount? ' - ' + this.model.constructInfo.reimbursementAmount :'')  //标题
    },
    async onSubmit() {
      await this.validateForm()
      this.isSubmit = true
      this.setBpmBizTitle()
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
        const response = await url({
          ...this.model,
        })
        if (response.success) {
          this.isSubmit = true
          if (this.id) {
            await this.getProcessList(this.id)
          } else {
            // 判断添加的时候是否有返回id值
            if (response.result) {
              await this.getProcessList(response.result)
            }
          }
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
              // that.isSubmit = false
            },
          })
        }
      } finally {
        this.loading = false
      }
    },
    async onDraft() {
      // await this.validateForm()
      this.isSubmit = true
      this.setBpmBizTitle()
      try {
        this.loading = true
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
        const response = await url({
          ...this.model,
        })
        if (response.success) {
          this.$refs.uToast.show({
            message: response.message,
            type: 'default',
            complete() {
              this.isSubmit = false
              if (getCurrentPages().length > 1) {
                uni.navigateBack()
              } else {
                uni.reLaunch({
                  url: '/pages/home/home',
                })
              }
            },
          })
        }
      } finally {
        this.loading = false
      }
    },
    // 获取流程列表
    getProcessList(id) {
      if (this.isSubmit) {
        this.$refs.processConfig.showPopup = true
        this.$refs.processConfig.formUrl = this.formUrl
        this.$refs.processConfig.formUrlMobile = this.formUrlMobile
        this.$refs.processConfig.flowCode = this.flowCode
        this.$refs.processConfig.edit(id, this.processId, this.beanName)
      }
    },
    // 提交流程成功
    onOk() {
      this.$refs.uToast.show({
        message: '提交成功',
        type: 'success',
        complete() {
          if (getCurrentPages().length > 1) {
            uni.navigateBack()
          } else {
            uni.reLaunch({
              url: '/pages/home/home',
            })
          }
        },
      })
    },
  },
  watch: {
    'model.applicant'(current, old) {
      if (old && current && old !== current) {
        this.backUpApplicant = old
        // this.resetMetaData()
      }
    },
    'model.projectBusiTeamId'(current, old) {
      if (old && current && old !== current) {
        this.backUpTeamId = old
        // this.resetMetaData()
      }
    },
  },
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');

.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
